<template>
  <div class="cart-container">
    <!-- 导航栏 -->
    <Navbar />
    
    <div class="container">
      <div class="cart-header">
        <h2><i class="fas fa-shopping-cart"></i> 购物车</h2>
        <span class="item-count">{{ cartItems.length }} 件商品</span>
      </div>

      <div v-if="cartItems.length === 0" class="empty-cart">
        <div class="empty-icon">
          <i class="fas fa-shopping-cart"></i>
        </div>
        <h3>购物车空空如也</h3>
        <p>去挑选一些心仪的商品吧</p>
        <button class="btn btn-primary" @click="$router.push('/products')">
          <i class="fas fa-box-open"></i>
          去选购商品
        </button>
      </div>

      <div v-else class="cart-content">
        <div class="cart-items">
          <div class="cart-header-row">
            <label class="checkbox-wrapper">
              <input 
                type="checkbox"
                v-model="selectAll" 
                @change="handleSelectAll($event)"
                :class="{ 'indeterminate': isIndeterminate }"
              />
              <span class="checkmark"></span>
              全选
            </label>
            <span>商品信息</span>
            <span>单价</span>
            <span>数量</span>
            <span>小计</span>
            <span>操作</span>
          </div>

          <div 
            v-for="item in cartItems" 
            :key="item.productId"
            class="cart-item"
          >
            <label class="checkbox-wrapper">
              <input 
                type="checkbox"
                v-model="item.selected"
                @change="updateSelectAll"
              />
              <span class="checkmark"></span>
            </label>
            
            <div class="product-info">
              <div class="product-image">
                <img 
                  v-if="item.productImage && item.productImage !== '/placeholder-product.png' && !item.imageError"
                  :src="item.productImage"
                  :alt="item.productName"
                  @error="handleImageError($event, item)"
                />
                <div v-else class="default-product-icon">
                  <el-icon><Cpu /></el-icon>
                </div>
              </div>
              <div class="product-details">
                <h4>{{ item.productName }}</h4>
                <p>{{ item.specParams || '标准规格' }}</p>
              </div>
            </div>

            <div class="product-price">
              ¥{{ formatPrice(item.price) }}
            </div>

            <div class="quantity-control">
              <button 
                class="quantity-btn"
                @click="decreaseQuantity(item)"
                :disabled="item.quantity <= 1"
              >
                <el-icon><Minus /></el-icon>
              </button>
              <input 
                type="number"
                v-model.number="item.quantity"
                @change="updateQuantity(item)"
                :min="1"
                :max="item.stock || 999"
                class="quantity-input"
              />
              <button 
                class="quantity-btn"
                @click="increaseQuantity(item)"
                :disabled="item.quantity >= (item.stock || 999)"
              >
                <el-icon><Plus /></el-icon>
              </button>
            </div>

            <div class="subtotal">
              ¥{{ formatPrice(item.price * item.quantity) }}
            </div>

            <div class="actions">
              <button 
                class="btn btn-sm btn-danger"
                @click="removeItem(item.productId)"
              >
                <i class="fas fa-trash"></i>
                删除
              </button>
            </div>
          </div>
        </div>

        <!-- 结算区域 -->
        <div class="checkout-section">
          <div class="checkout-summary">
            <div class="selected-items">
              <i class="fas fa-check-circle"></i>
              已选择 {{ selectedItems.length }} 件商品
            </div>
            <div class="action-buttons">
              <button 
                class="btn btn-danger btn-medium batch-delete-btn"
                @click="batchDeleteSelected"
                :disabled="selectedItems.length === 0"
                v-if="selectedItems.length > 0"
              >
                <i class="fas fa-trash"></i>
                删除选中 ({{ selectedItems.length }})
              </button>
            </div>
            <div class="total-price">
              <span class="label">合计:</span>
              <span class="amount">¥{{ formatPrice(totalAmount) }}</span>
            </div>
            <button 
              class="btn btn-primary btn-large checkout-btn"
              @click="checkout"
              :disabled="selectedItems.length === 0"
            >
              <i class="fas fa-credit-card"></i>
              结算 ({{ selectedItems.length }})
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 浮动购物车 -->
    <FloatingCart />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { Plus, Minus, Cpu } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'
import FloatingCart from '@/components/FloatingCart.vue'
import { message, confirm, feedback, batchConfirm } from '@/utils/message'

export default {
  name: 'CartView',
  components: {
    Navbar,
    FloatingCart,
    Plus,
    Minus,
    Cpu
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const selectAll = ref(false)
    
    const cartItems = computed(() => {
      const items = store.state.cart || []
      // 确保每个商品都有selected属性
      return items.map(item => ({
        ...item,
        selected: item.selected !== undefined ? item.selected : false,
        price: item.price || item.unitPrice || 0,
        productImage: item.productImage || '/placeholder-product.png'
      }))
    })
    
    const selectedItems = computed(() => 
      cartItems.value.filter(item => item.selected)
    )
    
    const totalAmount = computed(() => 
      selectedItems.value.reduce((total, item) => 
        total + (item.price * item.quantity), 0
      )
    )
    
    const isIndeterminate = computed(() => {
      const selectedCount = selectedItems.value.length
      return selectedCount > 0 && selectedCount < cartItems.value.length
    })
    
    const handleSelectAll = (event) => {
      const checked = event.target.checked
      cartItems.value.forEach(item => {
        item.selected = checked
      })
      store.dispatch('updateCartSelection', {
        selectAll: checked
      })
    }
    
    const updateSelectAll = () => {
      const allSelected = cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
      const noneSelected = cartItems.value.every(item => !item.selected)
      
      if (allSelected) {
        selectAll.value = true
      } else if (noneSelected) {
        selectAll.value = false
      } else {
        selectAll.value = false
      }
      
      // 更新store中的选择状态
      store.dispatch('updateCartSelection', {
        items: cartItems.value.map(item => ({
          productId: item.productId,
          selected: item.selected
        }))
      })
    }
    
    const updateQuantity = (item) => {
      if (item.quantity < 1) {
        item.quantity = 1
      }
      store.dispatch('updateCartQuantity', {
        productId: item.productId,
        quantity: item.quantity
      })
    }
    
    const increaseQuantity = (item) => {
      item.quantity += 1
      updateQuantity(item)
    }
    
    const decreaseQuantity = (item) => {
      if (item.quantity > 1) {
        item.quantity -= 1
        updateQuantity(item)
      }
    }
    
    const removeItem = async (productId) => {
      try {
        await confirm.delete('删除商品', '确定要删除这件商品吗？')
        store.dispatch('removeProductFromCart', productId)
        message.success('已删除商品')
        
        // 更新全选状态
        updateSelectAll()
      } catch (error) {
        // 用户取消删除
      }
    }
    
    const handleImageError = (event, item) => {
      item.imageError = true
      event.target.style.display = 'none'
    }
    
    const formatPrice = (price) => {
      return parseFloat(price || 0).toFixed(2)
    }
    
    const checkout = () => {
      if (selectedItems.value.length === 0) {
        message.warning('请选择要结算的商品')
        return
      }
      
      // 检查用户是否登录
      const user = store.state.user
      if (!user) {
        message.warning('请先登录')
        router.push('/login')
        return
      }
      
      // 将选中的商品存储到store中用于结算
      store.commit('setCheckoutItems', selectedItems.value)
      
      // 跳转到结算页面
      router.push('/checkout')
    }
    
    // 批量删除选中商品
    const batchDeleteSelected = async () => {
      if (selectedItems.value.length === 0) {
        message.warning('请先选择要删除的商品')
        return
      }
      
      try {
        await batchConfirm('删除', selectedItems.value.length, '件商品')
        
        const selectedIds = selectedItems.value.map(item => item.productId)
        const count = selectedIds.length
        
        // 逐个删除选中的商品
        selectedIds.forEach(productId => {
          store.dispatch('removeProductFromCart', productId)
        })
        
        message.success(`已删除 ${count} 件商品`)
        
        // 清除全选状态
        selectAll.value = false
      } catch (error) {
        // 用户取消删除
      }
    }

    // 初始化购物车数据
    onMounted(() => {
      // 如果购物车为空，可以从localStorage加载
      if (cartItems.value.length === 0) {
        store.dispatch('loadCartFromStorage')
      }
      
      // 初始化全选状态
      setTimeout(() => {
        updateSelectAll()
      }, 100)
    })

    return {
      selectAll,
      cartItems,
      selectedItems,
      totalAmount,
      isIndeterminate,
      handleSelectAll,
      updateSelectAll,
      updateQuantity,
      increaseQuantity,
      decreaseQuantity,
      removeItem,
      batchDeleteSelected,
      handleImageError,
      formatPrice,
      checkout
    }
  }
}
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #ffffff;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
}

.cart-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.cart-header h2 i {
  color: #00D4FF;
}

.item-count {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.empty-cart {
  text-align: center;
  padding: 80px 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
}

.empty-icon {
  font-size: 80px;
  color: #00D4FF;
  margin-bottom: 24px;
  opacity: 0.7;
}

.empty-cart h3 {
  font-size: 24px;
  color: #ffffff;
  margin: 0 0 12px 0;
}

.empty-cart p {
  font-size: 16px;
  color: #B0BEC5;
  margin: 0 0 32px 0;
}

.cart-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.cart-items {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  overflow: hidden;
}

.cart-header-row {
  display: grid;
  grid-template-columns: 100px 1fr 120px 150px 120px 100px;
  gap: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  font-weight: 600;
  color: #B0BEC5;
  font-size: 14px;
}

.cart-item {
  display: grid;
  grid-template-columns: 100px 1fr 120px 150px 120px 100px;
  gap: 16px;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  align-items: center;
  transition: background 0.3s ease;
}

.cart-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.cart-item:last-child {
  border-bottom: none;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #B0BEC5;
}

.checkbox-wrapper input[type="checkbox"] {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-wrapper input[type="checkbox"]:checked + .checkmark {
  background: #00D4FF;
  border-color: #00D4FF;
}

.checkbox-wrapper input[type="checkbox"]:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-wrapper input[type="checkbox"].indeterminate + .checkmark {
  background: #00D4FF;
  border-color: #00D4FF;
}

.checkbox-wrapper input[type="checkbox"].indeterminate + .checkmark::after {
  content: '';
  position: absolute;
  left: 3px;
  top: 7px;
  width: 8px;
  height: 2px;
  background: white;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-product-icon {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #00D4FF;
  background: rgba(255, 255, 255, 0.05);
}

.product-details {
  flex: 1;
}

.product-details h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
  line-height: 1.4;
}

.product-details p {
  margin: 0;
  font-size: 14px;
  color: #B0BEC5;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #00D4FF;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  color: #B0BEC5;
}

.quantity-btn:hover:not(:disabled) {
  border-color: #00D4FF;
  color: #00D4FF;
  background: rgba(0, 212, 255, 0.1);
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 60px;
  height: 32px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  text-align: center;
  font-size: 14px;
  padding: 0 8px;
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.quantity-input:focus {
  outline: none;
  border-color: #00D4FF;
  background: rgba(255, 255, 255, 0.15);
}

.subtotal {
  font-size: 18px;
  font-weight: 600;
  color: #00D4FF;
  text-align: right;
}

.actions {
  text-align: center;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: linear-gradient(45deg, #00B8E6, #3F3BE0);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}

.btn-danger {
  background: linear-gradient(45deg, #EF4444, #DC2626);
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: linear-gradient(45deg, #DC2626, #B91C1C);
  transform: translateY(-1px);
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-large {
  padding: 16px 32px;
  font-size: 16px;
  font-weight: 600;
}

.checkout-section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  overflow: hidden;
}

.checkout-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px;
  background: rgba(255, 255, 255, 0.05);
}

.selected-items {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #B0BEC5;
}

.selected-items i {
  color: #00D4FF;
}

.total-price {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
}

.total-price .label {
  color: #B0BEC5;
}

.total-price .amount {
  font-size: 24px;
  font-weight: 700;
  color: #00D4FF;
}

.checkout-btn {
  min-width: 200px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.batch-delete-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

.batch-delete-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

.batch-delete-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.btn-medium {
  padding: 12px 20px;
  font-size: 14px;
}

@media (max-width: 768px) {
  .container {
    padding: 12px;
  }
  
  .cart-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .cart-header-row,
  .cart-item {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .cart-header-row {
    display: none;
  }
  
  .cart-item {
    display: flex;
    flex-direction: column;
    align-items: stretch;
    padding: 16px;
  }
  
  .product-info {
    align-self: stretch;
  }
  
  .quantity-control {
    justify-content: center;
  }
  
  .checkout-summary {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .total-price {
    justify-content: center;
  }
}
</style> 